package com.gin.kotlin.no_gay_alliance.webview

import android.content.Context
import android.content.Intent
import android.view.Gravity
import android.view.View
import android.webkit.JavascriptInterface
import androidx.activity.result.ActivityResultLauncher
import androidx.annotation.MenuRes
import androidx.appcompat.widget.PopupMenu
import androidx.fragment.app.FragmentActivity
import com.gin.kotlin.no_gay_alliance.activity.PostActivity.Companion.obtainIntent
import com.gin.kotlin.no_gay_alliance.activity.UserCenterActivity
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.argument.PostPrepareArgument
import com.gin.kotlin.no_gay_alliance.argument.PostPrepareArgument.Action
import com.gin.kotlin.no_gay_alliance.base.PhotoPreviewUtils
import com.gin.kotlin.no_gay_alliance.listener.PhotoPreviewLongClickListener
import com.gin.nga.callback.NgaCallback
import com.gin.nga.enums.ImageThumb
import com.gin.nga.response.base.NgaResponse
import retrofit2.Call
import retrofit2.Response

/**
 * 为 [com.gin.kotlin.no_gay_alliance.webview.BbsCodeWebView] 提供方法调用接口
 */
interface JsAndroidInterface {
    /**
     * 启动器，用于启动回复、引用
     */
    val mLauncher: ActivityResultLauncher<Intent>

    /**
     * 活动，用于预览图片，启动发帖活动
     */
    val mActivity: FragmentActivity


    /**
     * 预览指定url的图片
     * @param url String
     */
    @JavascriptInterface
    fun previewByUrl(url: String) {
        // 打开预览的界面(缩略图所处界面)，预览生命周期与activity绑定
        var u = url

        // 移除缩略图后缀
        ImageThumb.entries.forEach {
            if (u.endsWith(it.suffix)) u = u.replace(it.suffix, "")
        }

        App.INSTANCE.handler?.post {
            PhotoPreviewUtils.build(mActivity, listOf(u), listener = PhotoPreviewLongClickListener(mActivity) { _ ->
                run {
                    // 检查链接形式，如果是附件格式转换为code
                    val code = if (u.startsWith(ImageThumb.PREFIX)) u.replace(ImageThumb.PREFIX, "").let { "[img]./$it[/img]" } else ""
                    PhotoPreviewLongClickListener.PreviewImage(u, code)
                }
            }).build().show()
        }
    }

    /**
     * 启动发帖：回复
     * @param topicId Long
     * @param replyId Long
     */
    @JavascriptInterface
    fun postReply(topicId: Long, replyId: Long) = mLauncher.launch(obtainIntent(mActivity, PostPrepareArgument(Action.REPLY, topicId = topicId, replyId = replyId)))

    /**
     * 启动发帖：引用
     * @param topicId Long
     * @param replyId Long
     */
    @JavascriptInterface
    fun postQuote(topicId: Long, replyId: Long) = mLauncher.launch(obtainIntent(mActivity, PostPrepareArgument(Action.QUOTE, topicId = topicId, replyId = replyId)))

    /**
     * 点赞
     * @param topicId Long
     * @param replyId Long
     */
    @JavascriptInterface
    fun agree(topicId: Long, replyId: Long) = App.INSTANCE.ngaApi.topicReadApi.agree(topicId, replyId).enqueue(object : NgaCallback<List<String>> {
        override fun onSuccess(call: Call<NgaResponse<List<String>>>, response: Response<NgaResponse<List<String>>>, body: NgaResponse<List<String>>?, data: List<String>?) {
            agreeCallback(replyId, body)
        }

        override fun onError(call: Call<NgaResponse<List<String>>>, response: Response<NgaResponse<List<String>>>, body: NgaResponse<List<String>>?, errorMessage: String) {
            super.onError(call, response, body, errorMessage)
            agreeCallback(replyId, body)
        }
    })

    /**
     * 点踩
     * @param topicId Long
     * @param replyId Long
     */
    @JavascriptInterface
    fun disagree(topicId: Long, replyId: Long) = App.INSTANCE.ngaApi.topicReadApi.disagree(topicId, replyId).enqueue(object : NgaCallback<List<String>> {
        override fun onSuccess(call: Call<NgaResponse<List<String>>>, response: Response<NgaResponse<List<String>>>, body: NgaResponse<List<String>>?, data: List<String>?) {
            agreeCallback(replyId, body)
        }

        override fun onError(call: Call<NgaResponse<List<String>>>, response: Response<NgaResponse<List<String>>>, body: NgaResponse<List<String>>?, errorMessage: String) {
            super.onError(call, response, body, errorMessage)
            agreeCallback(replyId, body)
        }
    })


    /**
     * 打开查询用户菜单：只看TA，用户主题，本版主题，本版精华，用户回复，本版回复
     * @param userId Long
     * @param topicId Long
     * @param forumId Long
     */
    @JavascriptInterface
    fun showQueryUserMenu(replyId: Long) = todo()

    /**
     * 打开更多菜单
     * @param replyId Long
     */
    @JavascriptInterface
    fun showMoreMenu(replyId: Long) = todo()

    /**
     * 启动活动：用户中心
     * @param userId Long
     */
    @JavascriptInterface
    fun openUserCenter(userId: Long) = UserCenterActivity.startActivity(mActivity, userId)

    /**
     * 打开历史版本(回复历史)
     * @param replyId Long
     */
    @JavascriptInterface
    fun showVersion(replyId: Long) = todo()

    /**
     * 打开附件列表
     * @param replyId Long
     */
    @JavascriptInterface
    fun showAttachments(replyId: Long) = todo()

    /**
     * 点赞或点踩的回调
     * @param replyId Long
     * @param body NgaResponse<List<String>>?
     */
    fun agreeCallback(replyId: Long, body: NgaResponse<List<String>>?) = todo()

    companion object {
        private fun todo() {
            App.INSTANCE.handler?.toastDevInProgress()
        }

        /**
         * 显示一个 [PopupMenu]
         * @param context Context
         * @param anchor View
         * @param menuId Int
         * @param listener OnMenuItemClickListener
         * @return PopupMenu
         */
        fun showPopupMenu(context: Context, anchor: View, @MenuRes menuId: Int, listener: PopupMenu.OnMenuItemClickListener) = PopupMenu(context, anchor).also {
            it.inflate(menuId)
            it.setForceShowIcon(true)
            it.setOnMenuItemClickListener(listener)
            it.gravity = Gravity.START
            it.show()
        }

    }
}